/*
左指针left:nums[left]>=x-k;
右指针right:nums[right]>x+k; 如果不存在则right=n
*/
class Solution {
public:
    int maxFrequency(vector<int>& nums, int k, int numOperations) {
        ranges::sort(nums);
        int n=nums.size();
        int ans=0, cnt=0, left=0, right=0, left2=0;
        for(int i=0; i<n; i++) {
            int x=nums[i];
            while(nums[left2]<x-k*2) left2++;
            ans=max(ans, min(i-left2+1, numOperations));
            cnt++;
            if(i<n-1&&x==nums[i+1]) continue; //循环知道连续相同段的末尾，统计出x的出现次数
            while(nums[left]<x-k) left++;
            while(right<n&&nums[right]<=x+k) right++;
            ans=max(ans, min(right-left, cnt+numOperations));
            cnt=0;
        }
        return ans;
    }
};